package com.mobi.Survey.lib.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.db.AbstractTable;
import com.mobi.Survey.lib.db.AlarmTable;
import com.mobi.Survey.lib.db.SurveyDetailTable;
import com.mobi.Survey.lib.exceptions.EmptyFieldException;
import com.mobi.Survey.lib.model.AlarmPojo;
import com.mobi.Survey.lib.model.SurveyDetailPojo;
import com.mobi.Survey.lib.model.SurveyPojo;
import com.mobi.Survey.lib.model.SurveyResultPojo;
import com.mobi.Survey.lib.model.User;
import com.mobi.Survey.lib.model.WebServiceIO;
import com.mobi.Survey.lib.uicomponents.ControlFactory;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyDetailScreen.java This class is responsible for displaying survey
 * detail. user passes survey id for this class
 */
public abstract class AbstractDetailScreen extends AbstractScreen {
	// Common Variables

	protected SurveyPojo survey;
	protected Button btnSubmit;
	protected ImageView ivBgImage;
	protected View parent;

	protected List<SurveyDetailPojo> sdps;
	protected List<View> views = new ArrayList<View>();
	protected List<Object> viewVids = new ArrayList<Object>();

	protected List<String> videoUrls = new ArrayList<String>();
	protected List<Bitmap> bitmapsVids = new ArrayList<Bitmap>();
	protected List<String> imageUrls = new ArrayList<String>();

	/**
	 * if single screen button will be added other wise image view will be added
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// hideTitle = true;
		super.onCreate(savedInstanceState);

		final Intent intent = getIntent();

		if (intent != null) {
			final Bundle bundle = intent.getExtras();
			if (bundle != null) {
				survey = bundle.getParcelable("data");

			}

		}

		setTitle(survey.getSurveyDiscription());
		final String bgColor = survey.getbGColor();
		if (null != bgColor && bgColor.length() > 0
				&& (null == survey.getbGImageUrl() || survey.getbGImageUrl().length() == 0)) {
			parent.setBackgroundColor(Color.parseColor("#" + bgColor));
		} else {
			parent.setBackgroundColor(Color.BLACK);
		}

		new LongTask().execute();

		// Set Header View background
		showHeaderImage(User.getInstance().getDetailImage());

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		System.exit(0);
	}

	@Override
	protected void onStart() {

		super.onStart();
		// if (User.getInstance().isShowAds() &&
		// Helper.isNetworkAvailable(getBaseContext()) && adsEnabled) {
		//
		// }
	}

	@Override
	protected void initUiVars() {
		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		parent = findViewById(R.id.parent);
		ivBgImage = (ImageView) findViewById(R.id.ivBgImage);

		headerImage = findViewById(R.id.headerImage);

	}

	/**
	 * creates controls dynamically on the base of survey detail data if survey
	 * type is single screen all controls are displayed other wise other
	 * controls are made invisible
	 */
	protected abstract void createViews();

	private void showDuplicateAnswerDialogue(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton(Messages.RESUBMIT_ANSWER, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						new ResultSubmitTask().execute();

					}
				}).setNegativeButton(Messages.CANCEL, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});

		AlertDialog alert = builder.create();
		alert.show();
	}

	protected void btnClick(View vi)

	{

		if (vi.getId() == R.id.btnSubmit) {
			if (SurveyResultPojo.isNew(survey.getId(), AbstractDetailScreen.this) == 0) {
				new ResultSubmitTask().execute();
			} else {
				showDuplicateAnswerDialogue(Messages.ALREADY_ANSWERED);
			}
		}

	}

	/**
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 *            <p>
	 *            If Survey Detail type was single screen we created Button for
	 *            Video and Image control so on user click we display image and
	 *            video in separate screen we also keep reference of our buttons
	 *            or image preview in a Collection to track user click
	 * 
	 */
	protected abstract void performActionOnVideoControl(SurveyDetailPojo surveyDetailPojo, View view);

	/**
	 * If single screen we will display button for image control other wise we
	 * will display image
	 * 
	 * @param surveyDetailPojo
	 * @param view
	 */
	protected abstract void performActionOnImageControl(SurveyDetailPojo surveyDetailPojo, View view);

	/**
	 * 
	 * @author Yahya Arshad Retrieve Image Survey detail data in background
	 *         after Retrieving create views on base of that data
	 */
	private class LongTask extends AsyncTask<Long, Integer, Integer> {
		ProgressDialog progressDialog = null;

		protected Integer doInBackground(Long... params) {

			AbstractTable at = new SurveyDetailTable(AbstractDetailScreen.this);

			sdps = ((SurveyDetailTable) at).getSurveyDetail(survey.getId());

			AlarmTable tb = new AlarmTable(getApplicationContext());
			try {
				if (sdps.size() == 0) {

					SurveyPojo downloaded = downloadSurveyDetail(survey.getId());
					sdps = downloaded.getSurveyDetail();
					SurveyDetailPojo.commit(getApplicationContext(), sdps, survey.getId());

					List<AlarmPojo> alarms = downloaded.getAlarms();

					for (AlarmPojo saveAlarm : alarms) {
						saveAlarm.setSurveyId(survey.getId());

						AlarmPojo.commit(saveAlarm, getApplicationContext());
					}

					List<AlarmPojo> futureALarms = tb.getUpComings();

					setupAlarms(futureALarms);

				}

				for (SurveyDetailPojo sdp : sdps) {
					sdp.setSurvey(survey);

				}
				SurveyResultPojo.writeSurveyResult(survey.getId(), sdps, AbstractDetailScreen.this);
			} catch (IOException e) {
				SurveyDetailPojo.deleteAllDetailBySurveyId(getApplicationContext(), survey.getId());
				return -1;
			} finally {
				tb.closeDB();
				at.closeDB();
			}

			return 1;

		}

		protected void onPostExecute(Integer result) {

			super.onPostExecute(result);
			createViews();
			progressDialog.dismiss();
			progressDialog = null;

			if (result == -1) {
				showAlert("Survey Detail Download Error !");
			}

		}

		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(AbstractDetailScreen.this, "", Messages.FETCHING_SURVEY_DETAIL);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	protected abstract void onEmptyFieldException(int controlIndex);

	/**
	 * 
	 * Submit user result to server on ok response submitted survey data will be
	 * entered to users database too.
	 */
	private class ResultSubmitTask extends AsyncTask<Long, Integer, Boolean> {
		private ProgressDialog progressDialog = null;
		private String message = "";

		protected Boolean doInBackground(Long... params) {
			boolean isSuccessfullySubmitted = false;
			try {
				ControlFactory.getUserInputs(sdps, views);
				String userId = getUserIdFromPreferences(AbstractDetailScreen.this);
				isSuccessfullySubmitted = WebServiceIO.submitResult(getResources()
						.getString(R.string.survey_submit_url), userId, survey.getId(), sdps);
				if (isSuccessfullySubmitted) {

					SurveyResultPojo.delete(survey.getId(), AbstractDetailScreen.this);
					SurveyResultPojo.commit(survey.getId(), sdps, AbstractDetailScreen.this);

				}

			} catch (JSONException ex) {
				message = "Survey submit failed due to invalid data.";
			} catch (final EmptyFieldException e) {
				message = e.getMessage();
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						onEmptyFieldException(e.getDataIndex());

					}
				});

			} catch (IOException e) {
				message = Messages.CONNECT_ERROR;

			} catch (Exception e) {
				message = Messages.NO_INTERNET_CONNECTION + " : " + e.getMessage();
			}
			return isSuccessfullySubmitted;
		}

		protected void onPostExecute(Boolean response) {

			super.onPostExecute(response);
			if (response) {

				SurveyListScreen.reSynch = true;
				showLongToast(Messages.SURVEY_SUBMITTED);
				finish();

			} else {

				showAlert(message);
			}
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(AbstractDetailScreen.this, "", Messages.SUBMITTING_SURVEY);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

}
